import { Devices } from "../../devices";
import { Printer } from "../../printer";

Page({
    data: {
        statusBarHeight: 44,
        //是否正在发现设备
        discovering: false,
        //设备列表
        devices: [],
        //已选设备
        selected_deviceId: "",
        //规定仅显示哪些名称的设备
        device_name: null
    },
    //由页面传送过来的打印对象
    printer: null,
    //是否自动连接上次保存的设备，并打印
    auto_print: false,
    //
    BLEPrinter_device_name: "BLEPrinter_device",
    //
    onLoad(options) {
        let self = this;
        //自定义设备名称（仅查询该名称的设备）
        let dn = options.device_name || null;
        if(dn !== null && dn !== ""){
            this.setData({
                device_name: dn
            });
        }
        //是否连接到上次连接的设备，然后自动打印
        let ap = options.auto_print || null;
        this.auto_print = ap === "true";
        //
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on("setPrinter", printer => {
            self.printer = printer;
            if(self.auto_print){
                //需要自动打印，从缓存中获取
                let deviceId = wx.getStorageSync(self.BLEPrinter_device_name);
                if(deviceId != null && deviceId != undefined && deviceId != ""){
                    if(self.data.discovering){
                        //停止发现设备
                        self.stopDiscover();
                    }
                    //尝试连接设备
                    Devices.connectDevice(deviceId, res => {
                        if(!res.error){
                            //连接设备成功，可以自动打印
                            self.setData({
                                selected_deviceId: deviceId,
                                devices: [
                                    {
                                        deviceId: deviceId,
                                        name: "常用设备",
                                        connected: false
                                    }
                                ]
                            },() => {
                                //打印
                                setTimeout(self.printTicket, 200);
                            });
                        }
                    });
                }
            }
        });
    },
    onUnload(){
        //页面离开的时候，清除所有
        if(this.data.selected_deviceId){
            Devices.disconnect(this.data.selected_deviceId);
        }
        Devices.stop();
    },
    onReady() {
        let self = this;
        //开始
        Devices.stop();
        Devices.start();
        //发现设备时
        Devices.onDeviceFound(device => {
            if(device.name.toString().toUpperCase() === this.data.device_name || this.data.device_name.length === 0){
                self.data.devices.push(device);
                self.setData({
                    devices: self.data.devices
                });
            }
        });
        //蓝牙已初始化
        Devices.onAdapterStateChange(res => {
            self.setData({
                discovering: res.discovering
            });
        });
        //设备断开连接
        Devices.onConnectionStateChange(res => {
            console.log(res.deviceId, res.connected ? "已连接" : "已断开");
            let devices = self.data.devices;
            let device = null;
            for(let i = 0; i<devices.length; i++){
                if(devices[i].deviceId === res.deviceId){
                    self.setData({
                        [`devices[${i}].connected`]: res.connected
                    });
                    device = devices[i];
                    device.connected = res.connected;
                }
            }
            if(device && res.connected){
                //更换
                wx.setStorageSync(self.BLEPrinter_device_name, device.deviceId);
            }
        });
    },
    //
    showMessage(text){
        wx.showModal({
            title: "提醒",
            content: text,
            showCancel: false,
            confirmText: "我知道了"
        });
    },
    //
    toggleDiscovery(){
        if(!this.data.discovering){
            this.startDiscover();
        }else{
            this.stopDiscover();
        }
    },
    //搜索开始
    startDiscover(){
        let self = this;
        Devices.discovery(res => {
            if(res.error){
                self.showMessage(res.message);
            }else {
                self.data.selected_deviceId = "";
            }
            self.setData({
                discovering: res.error === 0
            });
        });
    },
    //停止搜索
    stopDiscover(){
        let self = this;
        Devices.stopDiscovery(res => {
            if(res.error){
                self.showMessage(res.message);
            }
            self.setData({
                discovering: false
            });
        });
    },
    //选择
    selectDevice(e){
        const { id } = e.currentTarget.dataset;
        let device = Devices.getDeviceById(id);
        if(device !== null){
            this.setData({
                selected_deviceId: device.deviceId
            });
        }
        //停止发现设备
        this.stopDiscover();
    },
    //连接设备
    connectDevice(callback){
        if(this.data.device.deviceId !== "") {
            let self = this;
            Devices.connectDevice(this.data.device.deviceId, res => {
                if(res.error){
                    self.showMessage(res.message);
                }else{
                    //连接成功
                    self.setData({
                        device: res.device
                    });
                    if(typeof callback === "function"){
                        callback();
                    }
                }
            });
        }
        else{
            this.showMessage("先选择设备");
        }
    },
    //打印小票
    printTicket(){
        if(!this.printer){
            this.showMessage("没有需要打印的数据");
            return;
        }
        let selected_deviceId = this.data.selected_deviceId;
        let self = this;
        if(selected_deviceId != ""){
            wx.showModal({
                title: "打印提醒",
                content: "正在打印，请勿关闭页面，请等待小票打印完成后，再离开此页面，以免打印未完成。",
                cancelText: "知道了",
                confirmText: "打印结束",
                success: res =>{
                    if(res.confirm){
                        //路由返回
                        wx.navigateBack();
                    }
                }
            });
            this.printer.exec(selected_deviceId, res => {
                if(!res.error){
                    const eventChannel = this.getOpenerEventChannel();
                    eventChannel.emit("printSuccess");
                }else{
                    self.showMessage("打印失败：", res.message);
                }
            });
        }else{
            this.showMessage("未选择打印设备");
        }
    },
    //打印
    printTest(){
        let self = this;
        let order = {
            order_id: "202204210901",
            time: "2022-04-21 14:00:36",
            mall_name: "助小农大数据体验店-武鸣桥罗旗舰店",
            manager_name: "小农人",
            price: 3825,
            coupon: 300,
            discount: 50,
            pay_price: 3475,
            pros: [
                {
                    name: "40%乐土富安植物蛋白有机肥",
                    amount: 30,
                    price: 80
                },
                {
                    name: "啶虫咪50%",
                    amount: 15,
                    price: 35
                },
                {
                    name: "王铜",
                    amount: 10,
                    price: 90
                }
            ],
            lines: ["你知道我在等你妈？如果不知道的话就漆黑了，有本事去找点钱啊？", "你如果真的在乎我。", "我不在乎你！"]
        };
        //将订单商品列表转换成一个数组
        let pros = [];
        //表头
        pros.push(["名称", "数量", "单价"]);
        //列表
        for(let i=0; i<order.pros.length; i++){
            let pro = order.pros[i];
            pros.push([pro.name, pro.amount.toString(), pro.price.toFixed(2)])
        }
        let printer = new Printer("gb2312");
        printer.init()
            .newLine().printText(order.mall_name)
            .newLine().fillText("=")
            .newLine()
            .newLine().printText("订 单 号：" + order.order_id)
            .newLine().printText("开 单 员：" + order.manager_name)
            .newLine().printText("开单时间：" + order.time)
            .newLine()
            //打印一个表格的列表(列表数据，各列宽度，是否添加边框)
            .newLine().printTable(pros, [16, 4, 8], true)
            .newLine()
            .newLine().printText("总 金 额：" + order.price.toFixed(2))
            .newLine().printText("店铺优惠：" + order.discount.toFixed(2))
            .newLine().printText("厂家优惠：" + order.coupon.toFixed(2))
            .newLine()
            .newLine().printText("实收金额：" + order.pay_price.toFixed(2))
            .newLine()
            .newLine()
            .newLine();
        //
        console.log(printer.queue_data.join(""));
        //
        let device = self.data.device;
        if(device.deviceId != null && device.deviceId != undefined && device.deviceId != ""){
            if(device.connected)
                printer.exec(device.deviceId, res => {
                    if(!res.error){
                        wx.showToast({
                            icon: "success",
                            duration: 2000,
                            title: "打印完成"
                        });
                    }else{
                        self.showMessage(res.message);
                    }
                });
        }else{
            self.showMessage("未选择设备");
        }
    }
})
